package com.groupseven.backend.controller;

import com.groupseven.backend.domain.Menu.MenuItem;
import com.groupseven.backend.domain.ResultType;
import com.groupseven.backend.services.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;

    @GetMapping("/{Usertype}")
    public ResultType getMenuByRole(@PathVariable int Usertype){
        ResultType result = new ResultType(1,"查询成功",200);
        List<MenuItem> roots = menuService.getAllParentMenuItem();
        List<MenuItem> subs = menuService.getAllSubMenuItem();
        List<MenuItem> checkedroots = menuService.getMenuItemByRole(Usertype);
        List<MenuItem> checkedsubs = menuService.getSubMenuItemByRole(Usertype);
        List<Integer> checked = new ArrayList<>();
        for(MenuItem rootIterator : roots){
            List<MenuItem> temp = new ArrayList<>();
            for(MenuItem subIterator : subs){
                if(rootIterator.getMenuid()==subIterator.getParentid()){
                    temp.add(subIterator);
                }
            }
            if(temp.size()!=0){
                rootIterator.setSubs(temp);
            }
        }
        for(MenuItem rootIterator : checkedroots){
            checked.add(rootIterator.getMenuid());
            List<MenuItem> temp = new ArrayList<>();
            for(MenuItem subIterator : checkedsubs){
                if(checked.contains(subIterator.getMenuid())){

                } else {
                    checked.add(subIterator.getMenuid());
                }
                if(rootIterator.getMenuid()==subIterator.getParentid()){
                    temp.add(subIterator);
                }
            }
            if(temp.size()!=0){
                rootIterator.setSubs(temp);
            }
        }
        result.setMenuList(checked);
        result.setMenuTree(roots);
        result.setMyMenu(checkedroots);
        return result;
    }

    @PutMapping("/{Usertype}")
    public ResultType updateMenuForRole(@PathVariable int Usertype,@RequestParam int[] MyMenuList){
        System.out.println(Usertype);
        System.out.println(MyMenuList);
        Map<String,Object> query = new HashMap<String,Object>();
        query.put("Rolenumber",Usertype);
        query.put("menu",MyMenuList);
        System.out.println(query.get("Rolenumber"));
        System.out.println(query.get("menu").toString());
        return new ResultType(menuService.updateRoleMenus(Usertype,query),"修改成功！",200);
    }

}
